package pri.wallen.simpleConnectionPool;

import java.sql.Connection;
import java.util.LinkedList;

/**
 * 项目名称：DaemonThreadLab
 * 类名称：pri.wallen.simpleConnectionPool.ConnectionPool
 * 类描述： 简易的连接池实现
 * 创建人：Wallen Han
 * 创建时间：2018年03月21日 17:52
 */
public class ConnectionPool {
    // 拥有 一个 connection 列表
    private LinkedList<Connection> pool = new LinkedList<Connection>();

    public ConnectionPool(int initialSize) {
        if (initialSize > 0 ){
            for (int i = 0; i < initialSize; i++ ){
                pool.addLast(ConnectionDriver.createConnection());
            }
        }
    }

    /*
     * 释放 connection 连接
     */
    public void releaseConnection(Connection connection) {
        // 获得锁
        synchronized (pool) {
            pool.addLast(connection);
            // 归还 connection 后 通知等待的线程
            pool.notifyAll();
        }
    }


    public Connection fetchConnection(long  mills) throws InterruptedException {
        synchronized (pool) {
            // 不限定超时等待
            if (mills <= 0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            } else { // 限定超时等待时间
                long future = System.currentTimeMillis() + mills;
                long remaining = mills;

                while( pool.isEmpty() && remaining > 0){
                    pool.wait(remaining);
                    remaining = future - System.currentTimeMillis();
                }

                Connection result = null;
                if (!pool.isEmpty()) {
                    result = pool.removeFirst();
                }

                return result;
            }
        }
    }
}
